package com.example.controller;

import com.example.common.BusinessError;
import com.example.common.CommonError;
import com.example.common.CommonRes;
import com.example.common.PageData;
import com.example.dao.Permission;
import com.example.dao.Role;
import com.example.dao.RolePermission;
import com.example.service.PermissionService;
import com.example.service.RoleService;
import com.example.validation.DtoValidator;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 功能描述
 * 角色处理控制器
 *
 * @author: jimmy
 * @date: 2023年12月29日 10:27
 */
@RestController
@RequestMapping("/role")
public class RoleController {
    /**
     * 角色service
     */
    @Autowired
    private RoleService roleService;
    /**
     * 目录service
     */
    @Autowired
    private PermissionService permissionService;

    /**
     * 校验器
     */
    @Autowired
    private DtoValidator dtoValidator;

    /**
     * 分页查询角色
     *
     * @param pageNo      第几页
     * @param pageSize    每页显示的数量
     * @param authority   查询参数，角色名称
     * @param displayName 查询参数，显示名称
     * @return
     */
    @GetMapping("/page")
    public CommonRes page(@RequestParam("pageNo") int pageNo,
                          @RequestParam("pageSize") int pageSize,
                          @RequestParam(value = "authority", defaultValue = "") String authority,
                          @RequestParam(value = "displayName", defaultValue = "") String displayName) {
        Role role = new Role();
        role.setStartIndex(pageNo * pageSize);
        role.setPageSize(pageSize);
        role.setAuthority(authority);
        role.setDisplayName(displayName);
        Integer total = roleService.findCount(role);
        List<Role> rolesList = roleService.findRolesByPage(role);
        PageData<Role> roleData = new PageData<>();
        roleData.setTotal(total);
        roleData.setPageData(rolesList);
        return CommonRes.create(roleData);
    }


    /**
     * 根据角色id查询用户，检查角色是否被用户设置了，在角色删除时要做参考
     *
     * @param ids
     * @return
     */
    @GetMapping("/findUserCountByRoleIds")
    public CommonRes findUserCountByRoleIds(@RequestParam("ids[]") Long[] ids) {
        int result = roleService.findUserCountByRoleIds(ids);
        return CommonRes.create(result);
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping("/delete")
    public CommonRes delete(@RequestBody Long[] ids) {
        int result = roleService.deleteRoleByIds(ids);
        if (result > 0) {
            return CommonRes.create(null);
        } else {
            CommonError commonError = new CommonError(BusinessError.UNKNOWN_ERROR);
            return CommonRes.createError(commonError);
        }
    }

    /**
     * 新增角色
     *
     * @param role
     * @return
     */
    @PostMapping(value = "/addRole")
    public CommonRes addRole(@Valid @RequestBody Role role) {
        // com.example.aspect.ValidateAspect
        //通过aop校验传过来的用户实体类userDto

        //id是autoincrease
        role.setId(null);
        int result = roleService.insertRole(role);
        if (result > 0) {
            return CommonRes.create(null);
        } else {
            CommonError commonError = new CommonError(BusinessError.UNKNOWN_ERROR);
            return CommonRes.createError(commonError);
        }
    }

    /**
     * 修改角色
     *
     * @param role
     * @return
     */
    @PostMapping(value = "/modifyRole")
    public CommonRes modifyRole(@Valid @RequestBody Role role) {
        // com.example.aspect.ValidateAspect
        //通过aop校验传过来的用户实体类userDto

        int result = roleService.updateRole(role);
        if (result > 0) {
            return CommonRes.create(null);
        } else {
            CommonError commonError = new CommonError(BusinessError.UNKNOWN_ERROR);
            return CommonRes.createError(commonError);
        }
    }


    /**
     * 校验角色名称，角色名称不能重复
     *
     * @param rolename
     * @param id
     * @return
     */
    @GetMapping("/validateRolename")
    public CommonRes validateRolename(@RequestParam String rolename, @RequestParam Long id) {
        if (roleService.isRolenameExisted(rolename, id)) {
            return CommonRes.createError(null);
        } else {
            return CommonRes.create(null);
        }
    }


    /**
     * 根据角色id查询权限，此处将所有权限查出，角色id的作用是
     * 查出已经设置的权限
     *
     * @param roleId
     * @return
     */
    @GetMapping("/getAllPermission")
    public CommonRes getAllPermission(@RequestParam Long roleId) {
        //查出所有权限
        List<Permission> permissionList = permissionService.findAllPermissionsByRoleId(roleId);
        //一级目录
        List<Permission> permissionFirst = new ArrayList<>();
        //二级目录
        List<Permission> permissionSecond = new ArrayList<>();
        Map<Long, Permission> firstPh = new HashMap<>();
        for (Permission permission : permissionList) {
            if (permission.getPid() == null) {
                permissionFirst.add(permission);
                firstPh.put(permission.getId(), permission);
            } else {
                permission.setChildren(null);
                permissionSecond.add(permission);
            }
        }

        //把对应的二级目录设置给一级目录
        for (Permission permission : permissionFirst) {
            for (Permission second : permissionSecond) {
                if (second.getPid() == permission.getId()) {
                    permission.getChildren().add(second);
                }
            }
        }
        //根据角色查询相对应的权限id
        List<Long> permissionIds = permissionService.findPermissionIdsByRoleId(roleId);
        PermissionData permissionData = new PermissionData();
        permissionData.setCheckedList(permissionIds);
        permissionData.setPermissionList(permissionFirst);
        return CommonRes.create(permissionData);
    }

    /**
     * 权限设置返回对象
     */
    @Data
    private static class PermissionData {
        /**
         * 已经设置给角色的权限id
         */
        private List<Long> checkedList;
        /**
         * 所有权限的列表
         */
        private List<Permission> permissionList;
    }

    /**
     * 设置角色目录
     *
     * @param allData
     * @return
     */
    @PostMapping("/attachPermissionToRole")
    public CommonRes attachPermissionToRole(@RequestBody List<RolePermission> allData) {
        int result = permissionService.attachPermissionToRole(allData);
        if (result > 0) {
            return CommonRes.create(null);
        } else {
            CommonError commonError = new CommonError(BusinessError.UNKNOWN_ERROR);
            return CommonRes.createError(commonError);
        }
    }
}
